package dao

import (
	"errors"
	"go-bluebell/model"

	"gorm.io/gorm"
)

func CreatePost(p *model.Post) (err error) {
	return model.DB.Omit("CreateTime").Create(p).Error
}

func GetPostByID(postID int64) (post *model.Post, err error) {
	post = new(model.Post)
	err = model.DB.First(&post, postID).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			err = model.ErrorInvalidID
		}
	}
	return
}

func GetPostList(page, size int) (postList []*model.Post, err error) {
	// make 采用的是动态扩容的方式
	postList = make([]*model.Post, 0, 10)
	// 查询并组合我们想要的帖子数据
	err = model.DB.Limit(size).Offset((page - 1) * size).Find(&postList).Error
	return
}

// GetPostListByIDs 根据给定的id列表查询帖子数据
func GetPostListByIDs(ids []string) (postList []*model.Post, err error) {
	// 要将 原始sql语句 用 gorm 的方式来写

	//sqlStr := `select post_id, title, content, author_id, community_id, create_time
	//from post
	//where post_id in (?)
	//order by FIND_IN_SET(post_id, ?)
	//`
	//// https: //www.liwenzhou.com/posts/Go/sqlx/
	//query, args, err := sqlx.In(sqlStr, ids, strings.Join(ids, ","))
	//
	//if err != nil {
	//	return nil, err
	//}
	//query = db.Rebind(query)
	//err = db.Select(&postList, query, args...) // !!!!!!

	err = model.DB.Where("post_id in (?)", ids).
		//Order("FIND_IN_SET(post_id," + strings.Join(ids, ",") + ")").
		Find(&postList).Error

	return
}
